﻿using DataModels;
using DataModels.Entities.Base;
using DataModels.Entities.HomeService;
using DataModels.Enums.Home;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Services.AuthCore;
using Services.WorkOrder;
using SqlSugar;
using System.Configuration;
using System.Text.Json;
using WeChatServices;
using static DataModels.Enums.GeneralEnum;

namespace ScheduledTasks.HomeService
{
    public class OrderExpires : IScheduledTask
    {
        private readonly ILogger<OrderExpires> _logger;
        private readonly WeChatMessageHandler _messageHandler;
        protected readonly OauthService _oauthService;
        private SqlSugarClient _db;

        public OrderExpires(ILogger<OrderExpires> logger, WorkOrderService workOrder, IConfiguration configuration, OauthService oauthService)
        {
            _logger = logger;
            _messageHandler = new WeChatMessageHandler(configuration, oauthService);
            _oauthService = oauthService;
        }

        // 2小时执行一次
        public string Schedule => "0 0 */2 * * *";

        public async Task<Task> ExecuteAsync(SqlSugarClient db)
        {
            try
            {
                _db = db;
                await _db.BeginTranAsync();
                _logger.LogInformation("开始处理待支付过期订单，时间：{DateTime}", DateTime.Now);

                // 查询待支付过期订单
                var hsos = await _db.Queryable<HomeServiceOrder>()
                    .Where(hso => hso.IsDeleted == Status.Disable)
                    .Where(hso => hso.OrderStatus == HomeServcieOrderStatus.PendingPayment)
                    .Where(hso => hso.ExpireTime < DateTime.Now)
                    .ToListAsync();

                _logger.LogInformation("查询到 {Count} 个待支付过期订单", hsos.Count);

                if (hsos.Count != 0)
                {
                    // 检查创建时间超过20小时的记录
                    var expiredRecords = hsos.Where(x => x.CreateTime < DateTime.Now.AddHours(-20));
                    if (expiredRecords.Any())
                    {
                        // 发送模板消息
                        string appType = "fwh";
                        try
                        {
                            var accessToken = await _oauthService.GetAccessToken(appType);
                            string templateId = "SYUOjGekf1EiJsZX7hywuB34rUAzb1HO4cjVxJz7-YI";

                            foreach (var order in expiredRecords)
                            {
                                // 获取订单相关的客户信息 - 这里需要根据您的实际数据结构调整
                                // 假设订单中有客户信息或可以通过订单获取客户
                                var customer = await _db.Queryable<Customer>()
                                    .Where(c => c.UUID == order.CreateUserUUID)
                                    .FirstAsync();

                                if (customer == null || string.IsNullOrWhiteSpace(customer.mpopen_id))
                                    continue;

                                // 构造模板消息数据，根据模板要求设置
                                var fieldValues = new Dictionary<string, string>
                                {
                                        {"character_string13", order.OrderNo}, // 订单编号
                                        {"phone_number4", order.ContactPhone},   // 联系电话
                                        {"thing8", order.ProductName}         //商品名称
                                };
                                string pagePath = ""; // 点击模板跳转页面
                                string dataJson = _messageHandler.BuildTemplateMessageWithMultipleKeywords(
                                    customer.mpopen_id, templateId, pagePath, fieldValues);

                                var result = await _messageHandler.SendTemplateMessage(
                                    accessToken, customer.mpopen_id, templateId, dataJson);

                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "发送模板消息时发生异常");
                        }
                        _logger.LogInformation("发现 {Count} 个创建时间超过20小时的待支付记录", expiredRecords.Count());
                    }

                    // 更新订单状态为已取消
                    foreach (var order in hsos)
                    {
                        order.OrderStatus = HomeServcieOrderStatus.Cancelled;
                        order.UpdateTime = DateTime.Now;
                    }

                    var updateCount = await _db.Updateable(hsos).ExecuteCommandAsync();
                    _logger.LogInformation("成功更新 {Count} 个订单状态为已取消", updateCount);

                    // 记录订单历史
                    await RecordOrderHistories(hsos, "订单超时未支付，自动取消");
                }

                await _db.CommitTranAsync();
                _logger.LogInformation("待支付过期订单处理完成，时间：{DateTime}", DateTime.Now);
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                await _db.RollbackTranAsync();
                _logger.LogError(ex, "处理待支付过期订单时发生错误");
                return Task.CompletedTask;
            }
        }

        public async Task RecordOrderHistories(List<HomeServiceOrder> orders, string reason)
        {
            try
            {
                var histories = orders.Select(order =>
                {
                    HomeServiceOrderHistory history = JsonSerializer.Deserialize<HomeServiceOrderHistory>(
                           JsonSerializer.Serialize(order)
                       );
                    history.beizhu = reason;
                    return history;
                }).ToList();

                await _db.Insertable(histories).ExecuteCommandAsync();
                _logger.LogInformation("成功记录 {Count} 条订单历史", histories.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "记录订单历史时发生错误");
            }
        }
    }
}